﻿namespace FsWeb.Filters

open System;
open System.Data.Entity;
open System.Data.Entity.Infrastructure;
open System.Threading;
open System.Web.Mvc;
open WebMatrix.WebData;
//open NewBusiness.Domain.Uow.Data;
open StructureMap;

type SimpleMembershipInitializer() = 
   do 
#if DEBUG
     // Database.SetInitializer<Data.DataContext>(new DropCreateDatabaseIfModelChanges<Data.DataContext>())
#else 
     //Database.SetInitializer<DataContext>(null)
#endif
      try
         let c =  FsWeb.Global.Container.GetInstance<Data.DataContext>()
         match c.Database.Exists() with 
         | false -> (c :> IObjectContextAdapter).ObjectContext.CreateDatabase()
         | true -> ();
         if WebSecurity.Initialized then 
           ()
         else 
           WebSecurity.InitializeDatabaseConnection("DefaultConnection","UserProfile","Id","UserName", true);
      with 
         | :? System.Exception as ex -> raise (InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex))


type InitializeSimpleMembershipAttribute() =
 inherit ActionFilterAttribute()
    let mutable _initializer: SimpleMembershipInitializer = new SimpleMembershipInitializer();
    let mutable _initializerLock:Object = new Object();
    let mutable _isInitialized:bool = false;
    override this.OnActionExecuting(filterContext:ActionExecutingContext) =  LazyInitializer.EnsureInitialized(ref _initializer ,ref _isInitialized ,ref _initializerLock ) |> ignore;

    